

<!DOCTYPE html>
<html lang="zh-CN">

<head><meta name="generator" content="Hexo 3.9.0">
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>从源码角度看Fragment的启动流程及生命周期 基于AndroidX Fragment1.2.2 - 杨云召 | 博客</title>
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
  <meta name="google" content="notranslate">

  
  
  <meta name="description" content="从源码角度看Fragment的启动流程及生命周期 基于..."> 
  
  <meta name="author" content="杨云召（Flywith24）"> 

  
    <link rel="icon" href="/images/icons/favicon-16x16.png" type="image/png" sizes="16x16">
  
  
    <link rel="icon" href="/images/icons/favicon-32x32.png" type="image/png" sizes="32x32">
  
  
    <link rel="apple-touch-icon" href="/images/icons/apple-touch-icon.png" sizes="180x180">
  
  
    <meta rel="mask-icon" href="/images/icons/stun-logo.svg" color="#333333">
  
  
    <meta rel="msapplication-TileImage" content="/images/icons/favicon-144x144.png">
    <meta rel="msapplication-TileColor" content="#000000">
  

  <link rel="stylesheet" href="/css/style.css">

  
  <link rel="stylesheet" href="//at.alicdn.com/t/font_1445822_hhodbqn7tit.css">
  

  
  
  <link rel="stylesheet" href="https://cdn.bootcss.com/fancybox/3.5.7/jquery.fancybox.min.css">
  

  
  
  <link rel="stylesheet" href="https://cdn.bootcss.com/highlight.js/9.18.1/styles/xcode.min.css">
  

  <script>
    var CONFIG = window.CONFIG || {};
    var ZHAOO = window.ZHAOO || {};
    CONFIG = {
      isHome: false,
      fancybox: true,
      pjax: false,
      lazyload: {
        enable: true,
        loadingImage: '/images/theme/loading.gif',
      },
      donate: {
        enable: true,
        alipay: 'https://gitee.com/flywith24/Album/raw/master/img/20201015113301.jpg',
        wechat: 'https://gitee.com/flywith24/Album/raw/master/img/20201015112814.png'
      },
      motto: {
        api: '',
        default: '不人云亦云，只求接近真相.'
      },
      galleries: {
        enable: true
      },
      fab: {
        enable: true,
        alwaysShow: false
      },
      carrier: {
        enable: true
      },
      daovoice: {
        enable: true
      }
    }
  </script>

  

  
</head></html>
<body class="lock-screen">
  <div class="loading"></div>
  


<nav class="navbar">
  <div class="left"></div>
  <div class="center">从源码角度看Fragment的启动流程及生命周期 基于AndroidX Fragment1.2.2</div>
  <div class="right">
    <i class="iconfont iconmenu j-navbar-menu"></i>
  </div>
</nav>

  <nav class="menu">
  <div class="menu-wrap">
    <div class="menu-close">
      <i class="iconfont iconbaseline-close-px"></i>
    </div>
    <ul class="menu-content">
      
      
      
      
      <li class="menu-item"><a href="/ " class="underline"> 首页</a></li>
      
      
      
      
      <li class="menu-item"><a href="/archives " class="underline"> 归档</a></li>
      
      
      
      
      <li class="menu-item"><a href="/tags " class="underline"> 标签</a></li>
      
      
      
      
      <li class="menu-item"><a href="/categories " class="underline"> 分类</a></li>
      
      
      
      
      <li class="menu-item"><a href="/about " class="underline"> 关于</a></li>
      
    </ul>
    <div class="menu-copyright"><p>Copyright© 2017 - 2020 ❤️ Flywith24</p></div>
  </div>
</nav>
  <main id="main">
  <div class="container" id="container">
    <article class="article">
  <div class="wrap">
    <section class="head">
  <img   class="lazyload" data-original="https://gitee.com/flywith24/Album/raw/master/img/20201015094458.png" src=""  draggable="false">
  <div class="head-mask">
    <h1 class="head-title">从源码角度看Fragment的启动流程及生命周期 基于AndroidX Fragment1.2.2</h1>
    <div class="head-info">
      <span class="post-info-item"><i class="iconfont iconcalendar"></i>三月 10, 2020</span
        class="post-info-item">
      
      <span class="post-info-item"><i class="iconfont iconfont-size"></i>12597</span>
    </div>
  </div>
</section>
    <section class="main">
      <section class="content">
        <blockquote>
<p>笔者看过不少源码分析类的文章，动辄贴上大段代码，这种方式很容易打断读者的思路，所以很多时候看过这类文章感叹好文好文，却感觉什么都没记住，亦或者默默加入收藏却不知何时能去细心地研读。</p>
<p>所以本文不会过多介绍源码的细节，更多地是抛砖引玉，如果您看过本文后能够跟着本文的思路自己翻一下源码相信您就不会有我上述的体验了。</p>
<p>本文默认您已对 fragment 的生命周期有所了解，并清楚fragment的缘起与职责。这部分基础内容可移步 <a href="https://developer.android.com/guide/components/fragments" target="_blank" rel="noopener">fragment 官方文档</a> </p>
<p><strong>也即本文不会介绍 “what”，而是介绍 “how” 并且探讨一下 “why”</strong></p>
</blockquote>
<p>这里贴一下 androidx fragment 源码地址</p>
<p><a href="https://android.googlesource.com/platform/frameworks/support/+/refs/heads/androidx-master-dev/fragment/" target="_blank" rel="noopener">androidx fragment 官方源码地址</a></p>
<p>本文基于 androidx fragment 1.2.2 源码分析</p>
<figure class="highlight groovy"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs groovy">implementation <span class="hljs-string">"androidx.fragment:fragment-ktx:1.2.2"</span><br></code></pre></td></tr></table></figure>

<p>本文主要介绍fragment的启动流程，其他内容例如返回栈，会后续更新，敬请关注。欢迎在评论区下讨论。<a href="https://github.com/Flywith24/Flywith24-Fragment-Demo" target="_blank" rel="noopener">本文demo</a></p>
<p>既然我们都知道 “what”，不妨我们来思考一下 “how”</p>
<h2 id="分析前的思考"><a href="#分析前的思考" class="headerlink" title="分析前的思考"></a>分析前的思考</h2><p>请大家思考一个问题，我们知道fragment 的生命周期是与其宿主 activity 的生命周期息息相关的，也即 activity 的每次生命周期回调都会引发每个fragment的类似回调。</p>
<p>那么，如果让我们来实现这样的操作，应该怎么做？</p>
<blockquote>
<p> 猜测：在activity每个生命周期的节点，去操作fragment，让其执行相应的生命周期方法。</p>
</blockquote>
<p>思路有了，下面进行一些细节的确认。</p>
<ol>
<li>activity 要能操作 fragment，fragment 亦可操作 fragment，所以需要抽象出一个管理 fragment 的模型</li>
<li>activity 操作 fragment 的一系列动作，应该是互为可逆一组操作。例如添加 fragment 后，也应能移除 fragment</li>
<li>activity 对 fragment 的每组操作不应是单一的，例如可以在一次操作中在 activity 不同位置添加两个 fragment，同时该操作还应满足 2 ，具有可逆性</li>
</ol>
<p>对于第一条，我们抽象出一个可以管理 fragment 的模型，加入上下级的关系，即 activity 可管理其内部的 fragment，fragment 亦可管理其内部的 fragment。因此 fragment 同时充当着管理者与被管理者两种角色</p>
<p>对于后两条，相信在大学学过数据库的人会想到一种结构：<strong>事务（Transaction）</strong></p>
<blockquote>
<p> 事务是指一组原子性的操作，这些操作是不可分割的整体，要么全完成，要么全不完成，完成后可以回滚到完成前的状态</p>
</blockquote>
<p>因此，fragment 中两个最重要的概念出现了，<code>FragmentManager</code> 和 <code>FragmentTransaction</code></p>
<p><code>FragmentManager</code>  封装着对 fragment 操作的各种方法，<code>addFragment</code> <code>removeFragment</code> 等等，而 <code>FragmentActivity</code> 通过 <code>FragmentController</code> 来操作 <code>FragmentManager</code>  </p>
<p><code>FragmentTransaction</code> 封装对 fragment 容器进行的 fragment 操作，例如在容器1内添加一个 fragment，同时在容器2内替换fragment。</p>
<p>它们均为抽象类，需要具体的实现类。</p>
<p><code>FragmentManager</code> 的实现类为 <code>FragmentManagerImpl</code>，其内部逻辑已全部移至 <code>FragmentManager</code>  中，是个空实现。</p>
<p><code>FragmentTransaction</code> 的实现类为 <code>BackStackRecord</code> ，其内部引用了 <code>FragmentManager</code> 的实例 ，同时重写了父类的 四个 <code>commit</code> 相关的方法。</p>
<h2 id="看似最简单的启动流程"><a href="#看似最简单的启动流程" class="headerlink" title="看似最简单的启动流程"></a>看似最简单的启动流程</h2><p>现在让我们看一部分代码，平时在activity中我们是这样填充一个fragment的</p>
<figure class="highlight kotlin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs kotlin"><span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onCreate</span><span class="hljs-params">(savedInstanceState: <span class="hljs-type">Bundle</span>?)</span></span> &#123;<br>       <span class="hljs-keyword">super</span>.onCreate(savedInstanceState)<br>       <span class="hljs-comment">//避免旋转屏幕等场景 fragment 重叠的问题</span><br>       <span class="hljs-keyword">if</span> (savedInstanceState == <span class="hljs-literal">null</span>) &#123;<br>           supportFragmentManager<span class="hljs-comment">//步骤1</span><br>               .beginTransaction()<span class="hljs-comment">//步骤2</span><br>               .add(R.id.container, BlankFragment.newInstance())<span class="hljs-comment">//步骤3</span><br>               .commitNow()<span class="hljs-comment">//步骤4</span><br>       &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<ul>
<li><p>步骤1，实例化 <code>FragmentManagerImpl</code> 对象 (内部经历了一些转换，详情参见源码或查看demo注释)</p>
</li>
<li><p>步骤2，实例化 <code>BackStackRecord</code>对象，并在构造器中传入 <code>FragmentManager</code> 实例</p>
</li>
<li><p>步骤3，调用事务方法，对 fragment 容器进行相应的操作，本例表示在 id 为 <code>container</code> 容器内添加 <code>BlankFragment</code></p>
</li>
<li><p>步骤4，提交事务，交于 <code>FragmentManager</code> 处理</p>
</li>
</ul>
<p>在 terminal 敲入 <code>adb shell setprop log.tag.FragmentManager VERBOSE</code> 可开启<code>FragmentManager</code>的日志功能，过滤 <code>FragmentManager</code> ，日志如下：</p>
<p><img class="lazyload" data-original="https://gitee.com/flywith24/Album/raw/master/img/20200324084150.png" src="/2020/03/10/Jetpack-fragment-lifecycle/gif;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQImWNgYGBgAAAABQABh6FO1AAAAABJRU5ErkJggg==" alt="单fragment启动日志"></p>
<p>绿色部分为笔者手动添加的log，灰色和蓝色部分为 fragment 源码中的log</p>
<p>根据日志显示的流程，我们的猜测看似是正确的，“在 activity 每个生命周期的节点，去操作 fragment ，让其执行相应的生命周期方法”</p>
<p>其实这里是有干扰的，因为我们是在activity 的 <code>onCreate</code> 方法里 创建并提交 <code>FragmentTransaction</code> ，如果在 <code>onResume</code> 里调用呢？</p>
<p><img class="lazyload" data-original="https://gitee.com/flywith24/Album/raw/master/img/20200324084240.png" src="/2020/03/10/Jetpack-fragment-lifecycle/gif;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQImWNgYGBgAAAABQABh6FO1AAAAABJRU5ErkJggg==" alt="单fragment启动日志2"></p>
<p>WTF！</p>
<p>或许，我们的猜测有问题？看似调用 <code>commitNow</code> 后 fragment 的生命流程是自发进行的</p>
<p>那如果我们把调用挪到 <code>onPause</code> 呢？</p>
<p>打开 activity 并按下 home 键</p>
<p><img class="lazyload" data-original="https://gitee.com/flywith24/Album/raw/master/img/20200324084122.png" src="/2020/03/10/Jetpack-fragment-lifecycle/gif;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQImWNgYGBgAAAABQABh6FO1AAAAABJRU5ErkJggg==" alt="单fragment启动日志-onPause"></p>
<p>我知道好奇的读者会尝试在 <code>onStop</code> 中尝试一下，有惊喜。手动滑稽。</p>
<p>从这几段日志上来看，fragment 在提交事务后会自发进入自己的生命周期流程，而当其宿主 activity  生命周期发生变化时，fragment 的生命周期也跟随变化。</p>
<p>如果这么说比较抽象的话，我们可以看在 onPause 中显示fragment 的日志，当 Fragment 进入 onStart 生命周期后，如果是正常流程应该进入 onResume，但由于按下 home 键 activity进入onStop，fragment 也进入了 onStop 状态</p>
<p>因此，我们将之前的猜测进行扩展：</p>
<blockquote>
<ol>
<li>在activity每个生命周期的节点，去操作fragment，让其执行相应的生命周期方法</li>
<li>FragmentTransaction  被提交后 fragment 会进入自己的生命周期流程，但受 1 约束</li>
</ol>
</blockquote>
<p>那么我们的源码解读就从两个方向入手</p>
<h2 id="Activity-操作-Fragment-生命周期"><a href="#Activity-操作-Fragment-生命周期" class="headerlink" title="Activity 操作 Fragment 生命周期"></a>Activity 操作 Fragment 生命周期</h2><p>activity 是通过 <code>FragmentController</code>  操作  <code>FragmentManager</code>  进而操作 fragment 的。</p>
<p>具体点就是在 activity 各个生命周期节点通过调用 <code>FragmentController</code> 中的各个 <code>dispatch-</code> 方法进而调用 <code>FragmentManager</code> 中的各个 <code>dispatch-</code> 方法</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">//FragmentActivity.java</span><br><span class="hljs-keyword">final</span> FragmentController mFragments = FragmentController.createController(<span class="hljs-keyword">new</span> HostCallbacks());<br><br><span class="hljs-comment">//以下代码省略部分逻辑</span><br><span class="hljs-meta">@Override</span><br><span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title">onCreate</span><span class="hljs-params">(@Nullable Bundle savedInstanceState)</span> </span>&#123;<br>    mFragments.dispatchCreate();<br>&#125;<br><br><span class="hljs-meta">@Override</span><br><span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title">onStart</span><span class="hljs-params">()</span> </span>&#123;<br>    mFragments.dispatchStart();<br>&#125;<br><br><span class="hljs-comment">//onResume 彻底执行完毕的回调</span><br><span class="hljs-meta">@Override</span><br><span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title">onPostResume</span><span class="hljs-params">()</span> </span>&#123;<br>    mFragments.dispatchResume();<br>&#125;<br><span class="hljs-meta">@Override</span><br><span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title">onPause</span><span class="hljs-params">()</span> </span>&#123;<br>    mFragments.dispatchPause();<br>&#125;<br><br><span class="hljs-meta">@Override</span><br><span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title">onStop</span><span class="hljs-params">()</span> </span>&#123;<br>    mFragments.dispatchStop();<br>&#125;<br><br><span class="hljs-meta">@Override</span><br><span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title">onDestroy</span><span class="hljs-params">()</span> </span>&#123;<br>    <span class="hljs-keyword">super</span>.onDestroy();<br>    mFragments.dispatchDestroy();<br>&#125;<br></code></pre></td></tr></table></figure>

<p>这样猜测 1 就被证实了</p>
<p><strong>activity 会在各个生命周期节点通过 <code>FragmentController</code> 间接调用 <code>FragmentManager</code>  中的 各种 <code>dispatch-</code> 方法，进而影响 fragment 的生命周期</strong></p>
<p>那么嵌套 fragment 呢？</p>
<p>嵌套 fragment 也应该是宿主使用 <code>FragmentManager</code>  中的各种 <code>dispatch-</code> 方法，基于这个想法我们可以看一下 <code>FragmentManager</code>  中 <code>dispatch-</code> 方法的调用</p>
<p><img class="lazyload" data-original="https://gitee.com/flywith24/Album/raw/master/img/20200324084349.png" src="/2020/03/10/Jetpack-fragment-lifecycle/gif;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQImWNgYGBgAAAABQABh6FO1AAAAABJRU5ErkJggg==" alt="dispatch-方法的引用"></p>
<p>可以看到这里有两处调用，第二处为activity 通过 <code>FragmentController</code> 间接调用，第一处使用的是 <code>mChildFragmentManager</code></p>
<p><strong>这里引出 fragment 中另外两个比较重要的概念，<code>getParentFragmentManager()</code> 和 <code>getChildFragmentManager()</code></strong></p>
<blockquote>
<p>注意：<code>requireFragmentManager()</code> 和 <code>getFragmentManager</code> 已弃用</p>
</blockquote>
<p><code>getChildFragmentManager()</code>获取的是fragment 中的 <code>mChildFragmentManager</code></p>
<p><code>getParentFragmentManager()</code> 获取的是fragment 中的 <code>mFragmentManager</code></p>
<p><code>mChildFragmentManager</code> 为fragment内部的 <code>fragmentManager</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">// Private fragment manager for child fragments inside of this one.</span><br><span class="hljs-meta">@NonNull</span><br>FragmentManager mChildFragmentManager = <span class="hljs-keyword">new</span> FragmentManagerImpl();<br></code></pre></td></tr></table></figure>

<p><code>mFragmentManager</code> 稍显复杂，</p>
<ol>
<li>如果 fragment 的直接宿主是 activity ，则返回的是 activity 中的<code>getSupportFragmentManager()</code> 返回的 <code>fragmentManager</code></li>
<li>如果 fragment 的直接宿主是 fragment，即该 fragment 是其他 fragment 的子 fragment，则返回的是其父 fragment 的 <code>getChildFragmentManager</code></li>
</ol>
<p><strong>所以 嵌套fragment 的生命周期是父 fragment 在各个生命周期节点上通过 <code>mChildFragmentManager</code> 调用 <code>dispatch-</code>  以影响其子 fragment 的生命周期</strong></p>
<p>这样我们第一部分的解读就告一段落了, 这里点到为止,一些细节需要您自己亲自看看源码</p>
<h2 id="Fragment-的生命周期自治"><a href="#Fragment-的生命周期自治" class="headerlink" title="Fragment 的生命周期自治"></a>Fragment 的生命周期自治</h2><p>在 <code>看似最简单的启动流程</code> 一节中我们分别在 activity 的 onCreate ，onResume，onPause 中分别开启并提交事务，来观察 fragment 的生命周期日志。</p>
<p>在没有 activity 干扰的情况下，fragment 的生命周期是自治的。</p>
<p>那么我们继续思考一个问题</p>
<p>Fragment 的生命周期是如何一环扣一环的执行的？</p>
<p>从上面的日志，我们看到很多 “moveto-” 的日志，</p>
<p><strong>我们可以继续大胆地猜测，一个生命周期节点结束后调用进入另一个生命周期节点的方法</strong></p>
<p>基于这个猜测，我们确认一些细节</p>
<p>fragment 应该有自己的状态，它可能自己管理内部的状态，也可能会有封装着状态转移的逻辑的专门管理状态的抽象</p>
<p>这里引出另外一个概念 <code>FragmentStateManager</code></p>
<p><code>FragmentStateManager</code> 中持有 fragment 的引用 <code>mFragment</code> 以及 <code>FragmentManager</code> 的状态 <code>mFragmentManagerState</code></p>
<p>这里fragment的状态值为：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> INITIALIZING = -<span class="hljs-number">1</span>;    <span class="hljs-comment">// Not yet attached.</span><br><span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> ATTACHED = <span class="hljs-number">0</span>;         <span class="hljs-comment">// Attached to the host.</span><br><span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> CREATED = <span class="hljs-number">1</span>;          <span class="hljs-comment">// Created.</span><br><span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> ACTIVITY_CREATED = <span class="hljs-number">2</span>; <span class="hljs-comment">// Fully created, not started.</span><br><span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> STARTED = <span class="hljs-number">3</span>;          <span class="hljs-comment">// Created and started, not resumed.</span><br><span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> RESUMED = <span class="hljs-number">4</span>;          <span class="hljs-comment">// Created started and resumed.</span><br></code></pre></td></tr></table></figure>

<p><code>FragmentStateManager</code> 还封装着 fragment 状态转移的方法，例如：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">activityCreated</span><span class="hljs-params">()</span> </span>&#123;<br>    <span class="hljs-keyword">if</span> (FragmentManager.isLoggingEnabled(Log.DEBUG)) &#123;<br>        Log.d(TAG, <span class="hljs-string">"moveto ACTIVITY_CREATED: "</span> + mFragment);<br>    &#125;<br>    mFragment.performActivityCreated(mFragment.mSavedFragmentState);<br>&#125;<br><span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">start</span><span class="hljs-params">()</span> </span>&#123;<br>    <span class="hljs-keyword">if</span> (FragmentManager.isLoggingEnabled(Log.DEBUG)) &#123;<br>        Log.d(TAG, <span class="hljs-string">"moveto STARTED: "</span> + mFragment);<br>    &#125;<br>    mFragment.performStart();<br>&#125;<br></code></pre></td></tr></table></figure>

<p>fragment 生命周期自治的核心逻辑封装在 <code>FragmentManager</code> 中的 <code>void moveToState(@NonNull Fragment f, int newState)</code>  内，主要代码为(精简后)：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">moveToState</span><span class="hljs-params">(@NonNull Fragment f, <span class="hljs-keyword">int</span> newState)</span> </span>&#123;<br>    FragmentStateManager fragmentStateManager = mFragmentStore.getFragmentStateManager(f.mWho);<br><br>    newState = Math.min(newState, fragmentStateManager.computeMaxState());<br>    <span class="hljs-keyword">if</span> (f.mState &lt;= newState) &#123;<br>        <span class="hljs-keyword">switch</span> (f.mState) &#123;<br>            <span class="hljs-keyword">case</span> Fragment.INITIALIZING:<br>                <span class="hljs-keyword">if</span> (newState &gt; Fragment.INITIALIZING) &#123;<br>                    fragmentStateManager.attach(mHost, <span class="hljs-keyword">this</span>, mParent);<br>                &#125;<br>            <span class="hljs-keyword">case</span> Fragment.ATTACHED:<br>                <span class="hljs-keyword">if</span> (newState &gt; Fragment.ATTACHED) &#123;<br>                    fragmentStateManager.create();<br>                &#125;<br>            <span class="hljs-keyword">case</span> Fragment.CREATED:<br>                <span class="hljs-keyword">if</span> (newState &gt; Fragment.INITIALIZING) &#123;<br>                    fragmentStateManager.ensureInflatedView();<br>                &#125;<br>                <span class="hljs-keyword">if</span> (newState &gt; Fragment.CREATED) &#123;<br>                    fragmentStateManager.createView(mContainer);<br>                    fragmentStateManager.activityCreated();<br>                    fragmentStateManager.restoreViewState();<br>                &#125;<br>            <span class="hljs-keyword">case</span> Fragment.ACTIVITY_CREATED:<br>                <span class="hljs-keyword">if</span> (newState &gt; Fragment.ACTIVITY_CREATED) &#123;<br>                    fragmentStateManager.start();<br>                &#125;<br>            <span class="hljs-keyword">case</span> Fragment.STARTED:<br>                <span class="hljs-keyword">if</span> (newState &gt; Fragment.STARTED) &#123;<br>                    fragmentStateManager.resume();<br>                &#125;<br>        &#125;<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<blockquote>
<p>注意：这里的switch 没有 break</p>
</blockquote>
<p>细心的读者可能发现了，fragment 中的状态怎么只到 resume ，后续的状态呢？</p>
<p>我们可以看一下 <code>FragmentManager</code> 中的 <code>dispatchPause</code> 方法</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">dispatchPause</span><span class="hljs-params">()</span> </span>&#123;<br>    dispatchStateChange(Fragment.STARTED);<br>&#125;<br></code></pre></td></tr></table></figure>

<p>为什么 dispatch 了 <code>STARTED</code> 的状态？其实刚刚 <code>moveToState</code> 方法我精简掉了一部分代码，留下的只有 <code>f.mState &lt;= newState</code> 的逻辑，即 <strong>dispatch 的新状态大于等于当前的状态</strong></p>
<p>而现在dispatch 的新状态比当前状态值小，则走了下面的逻辑，例如当前状态为 RESUMED ，新传递的状态为 STARTED，执行了 <code>fragmentStateManager.pause();</code> </p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">moveToState</span><span class="hljs-params">(@NonNull Fragment f, <span class="hljs-keyword">int</span> newState)</span> </span>&#123;<br>    FragmentStateManager fragmentStateManager = mFragmentStore.getFragmentStateManager(f.mWho);<br><br>    newState = Math.min(newState, fragmentStateManager.computeMaxState());<br>    <span class="hljs-keyword">if</span> (f.mState &lt;= newState) &#123;<br>    	<span class="hljs-comment">//省略...   </span><br>    &#125;<span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (f.mState &gt; newState) &#123;<br>        <span class="hljs-keyword">switch</span> (f.mState) &#123;<br>            <span class="hljs-keyword">case</span> Fragment.RESUMED:<br>                <span class="hljs-keyword">if</span> (newState &lt; Fragment.RESUMED) &#123;<br>                    fragmentStateManager.pause();<br>                &#125;<br>                <br>            <span class="hljs-keyword">case</span> Fragment.STARTED:<br>                <span class="hljs-keyword">if</span> (newState &lt; Fragment.STARTED) &#123;<br>                    fragmentStateManager.stop();<br>                &#125;<br>                <br>            <span class="hljs-keyword">case</span> Fragment.ACTIVITY_CREATED:<br>                <span class="hljs-keyword">if</span> (newState &lt; Fragment.ACTIVITY_CREATED) &#123;<br>                    <span class="hljs-keyword">if</span> (isLoggingEnabled(Log.DEBUG)) &#123;<br>                        Log.d(TAG, <span class="hljs-string">"movefrom ACTIVITY_CREATED: "</span> + f);<br>                    &#125;<br>                    <span class="hljs-keyword">if</span> (f.mView != <span class="hljs-keyword">null</span>) &#123;<br>                        <span class="hljs-keyword">if</span> (mHost.onShouldSaveFragmentState(f) &amp;&amp; f.mSavedViewState == <span class="hljs-keyword">null</span>) &#123;<br>                            fragmentStateManager.saveViewState();<br>                        &#125;<br>                    &#125;<br>                    <span class="hljs-keyword">if</span> (mExitAnimationCancellationSignals.get(f) == <span class="hljs-keyword">null</span>) &#123;<br>                        destroyFragmentView(f);<br>                    &#125; <span class="hljs-keyword">else</span> &#123;<br>                        f.setStateAfterAnimating(newState);<br>                    &#125;<br>                &#125;<br>            <span class="hljs-keyword">case</span> Fragment.CREATED:<br>                <span class="hljs-keyword">if</span> (newState &lt; Fragment.CREATED) &#123;<br>                    <span class="hljs-keyword">boolean</span> beingRemoved = f.mRemoving &amp;&amp; !f.isInBackStack();<br>                    <span class="hljs-keyword">if</span> (beingRemoved || mNonConfig.shouldDestroy(f)) &#123;<br>                        makeInactive(fragmentStateManager);<br>                    &#125; <span class="hljs-keyword">else</span> &#123;<br>                        <span class="hljs-keyword">if</span> (f.mTargetWho != <span class="hljs-keyword">null</span>) &#123;<br>                            Fragment target = findActiveFragment(f.mTargetWho);<br>                            <span class="hljs-keyword">if</span> (target != <span class="hljs-keyword">null</span> &amp;&amp; target.getRetainInstance()) &#123;<br>                                f.mTarget = target;<br>                            &#125;<br>                        &#125;<br>                    &#125;<br>                    <span class="hljs-keyword">if</span> (mExitAnimationCancellationSignals.get(f) != <span class="hljs-keyword">null</span>) &#123;<br>                        f.setStateAfterAnimating(newState);<br>                        newState = Fragment.CREATED;<br>                    &#125; <span class="hljs-keyword">else</span> &#123;<br>                        fragmentStateManager.destroy(mHost, mNonConfig);<br>                    &#125;<br>                &#125;<br>            <span class="hljs-keyword">case</span> Fragment.ATTACHED:<br>                <span class="hljs-keyword">if</span> (newState &lt; Fragment.ATTACHED) &#123;<br>                    fragmentStateManager.detach(mNonConfig);<br>                &#125;<br>        &#125;<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<blockquote>
<p>注意：这里的switch 还是没有 break</p>
</blockquote>
<p>这里有个细节，由于activity没有 onDestroyView 的生命周期，所以 <code>FragmentController</code> 中的 <code>dispatchDestroyView</code> 是没有调用的</p>
<p><img class="lazyload" data-original="https://gitee.com/flywith24/Album/raw/master/img/20200324084417.png" src="/2020/03/10/Jetpack-fragment-lifecycle/gif;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQImWNgYGBgAAAABQABh6FO1AAAAABJRU5ErkJggg==" alt="dispatchOnDestroyView"></p>
<p> 在 activity 中的 destroy 方法中通过 <code>fragmentController</code> 调用了 <code>dispatchDestroy</code> 内部调用 <code>dispatchStateChange(Fragment.INITIALIZING)</code> ，而此时的fragment 的 mState 为 <code>ACTIVITY_CREATED</code>，所以 <code>moveToState</code> 方法会走到 <code>ACTIVITY_CREATED</code> 的 case 并执行到底</p>
<p>这样 fragment 最简单场景的生命周期就结束了</p>
<h2 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h2><p>我们做一个总结：activity 和 fragment 会在各个生命周期节点通过被调用 fragment 的 <code>parentFragmentManager</code>（或者说父 fragment 的 <code>childFragmentManager</code> 和 activity 的 <code>supportFragmentManager</code>）中的各种 <code>dispatch-</code> 方法以影响子 fragment 的 生命周期，同时子 fragment 也拥有自己生命周期的调用链（从状态A转移至状态B）</p>
<p>不得不说 fragment 的很多 API 并不是很好用，从 androidx fragment 的更新频率也可以看出。比如 fragment 中的 view 和 fragment本身的生命周期是不一致的，存在onDestroyView 但 fragment没有销毁的情况</p>
<p><a href="https://medium.com/@ianhlake" target="_blank" rel="noopener">Ian Lake</a> 在 <a href="https://www.youtube.com/watch?v=RS1IACnZLy4" target="_blank" rel="noopener">Fragments: Past, Present, and Future (Android Dev Summit ‘19)</a> 中提到未来官方会将二者合并，届时 fragment 的使用会更加简洁</p>
<p>这里引用 <a href="https://medium.com/androiddevelopers/the-android-lifecycle-cheat-sheet-part-iii-fragments-afc87d4f37fd" target="_blank" rel="noopener">The Android Lifecycle cheat sheet — part III : Fragments</a> 文中的图片 ，和我画的commit <code>FragmentTransaction</code>  的脑图（略简陋），帮您更好的理解</p>
<p><img class="lazyload" data-original="https://gitee.com/flywith24/Album/raw/master/img/20200324084444.png" src="/2020/03/10/Jetpack-fragment-lifecycle/gif;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQImWNgYGBgAAAABQABh6FO1AAAAABJRU5ErkJggg==" alt=" [The Android Lifecycle cheat sheet — part III : Fragments](https://medium.com/androiddevelopers/the-android-lifecycle-cheat-sheet-part-iii-fragments-afc87d4f37fd)"></p>
<p><img class="lazyload" data-original="https://gitee.com/flywith24/Album/raw/master/img/20200324084515.png" src="/2020/03/10/Jetpack-fragment-lifecycle/gif;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQImWNgYGBgAAAABQABh6FO1AAAAABJRU5ErkJggg==" alt="fragment脑图"></p>
<p>强烈建议您自己亲自看一看源码，不然就变为我文章开头时说的状态了。</p>
<hr>
<h2 id="关于我"><a href="#关于我" class="headerlink" title="关于我"></a>关于我</h2><hr>
<p>我是 <a href="https://flywith24.gitee.io/">Fly_with24</a></p>
<ul>
<li><p><a href="https://juejin.im/user/57c7f6870a2b58006b1cfd6c" target="_blank" rel="noopener">掘金</a></p>
</li>
<li><p><a href="https://www.jianshu.com/u/3d5ad6043d66" target="_blank" rel="noopener">简书</a></p>
</li>
<li><p><a href="https://github.com/Flywith24" target="_blank" rel="noopener">Github</a></p>
</li>
</ul>
      </section>
      <section class="extra">
        
        <ul class="copyright">
  
  <li><strong>本文作者：</strong>杨云召（Flywith24）</li>
  <li><strong>本文链接：</strong><a href="https://flywith24.gitee.io/2020/03/10/Jetpack-fragment-lifecycle/index.html">https://flywith24.gitee.io/2020/03/10/Jetpack-fragment-lifecycle/index.html</a></li>
  <li><strong>版权声明：</strong>本博客所有文章均采用<a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh"
      rel="external nofollow" target="_blank"> BY-NC-SA </a>许可协议，转载请注明出处！</li>
  
</ul>
        
        
        <section class="donate">
  <div class="qrcode">
    <img   class="lazyload" data-original="https://gitee.com/flywith24/Album/raw/master/img/20201015113301.jpg" src="" >
  </div>
  <div class="icon">
    <a href="javascript:;" id="alipay"><i class="iconfont iconalipay"></i></a>
    <a href="javascript:;" id="wechat"><i class="iconfont iconwechat-fill"></i></a>
  </div>
</section>
        
        
  <ul class="tag-list"><li class="tag-list-item"><a class="tag-list-link" href="/tags/Jetpack/">Jetpack</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/MVVM/">MVVM</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/androidx/">androidx</a></li></ul>

        
<nav class="nav">
  
    <a href="/2020/03/14/Jetpack-OnBackPressedDispatcher/"><i class="iconfont iconleft"></i>Fragment返回栈预备篇 OnBackPressedDispatcher</a>
  
  
    <a href="/2020/03/02/Jetpack-fragment/">你真的会用Fragment吗？Fragment常见问题以及androidx下Fragment的使用新姿势<i class="iconfont iconright"></i></a>
  
</nav>

      </section>
      
      <section class="comments">
  
  <div class="btn" id="comments-btn">查看评论</div>
  
  
<div id="valine"></div>
<script defer src="//unpkg.com/valine/dist/Valine.min.js"></script>
<script>
  window.onload = function () {
    var loadValine = function () {
      new Valine({
        el: '#valine',
        app_id: "SHA3gzCcxFlqaPcGRnX4UgET-gzGzoHsz",
        app_key: "OYo7ITS4AzTvBUvb1yIY8oaf",
        placeholder: "期待你的留言",
        avatar: "mp",
        pageSize: "10",
        lang: "zh-CN",
      });
    }
    if ( true ) {
      $("#comments-btn").on("click", function () {
        $(this).hide();
        loadValine();
      });
    } else {
      loadValine();
    }
  };
</script>

</section>
      
    </section>
  </div>
</article>
  </div>
</main>
  <footer class="footer">
  <div class="footer-social">
    
    
    
    
    
    <a href="tencent://message/?Menu=yes&uin=1032367864 " target="_blank" onMouseOver="this.style.color= '#12B7F5'"
      onMouseOut="this.style.color='#33333D'">
      <i class="iconfont footer-social-item  iconQQ "></i>
    </a>
    
    
    
    
    
    <a href="javascript:; " target="_blank" onMouseOver="this.style.color= '#8bc34a'"
      onMouseOut="this.style.color='#33333D'">
      <i class="iconfont footer-social-item  iconwechat-fill "></i>
    </a>
    
    
    
    
    
    <a href="https://flywith24.gitee.io/about/ " target="_blank" onMouseOver="this.style.color= '#d32f2f'"
      onMouseOut="this.style.color='#33333D'">
      <i class="iconfont footer-social-item  iconheart "></i>
    </a>
    
    
    
    
    
    <a href="https://github.com/Flywith24 " target="_blank" onMouseOver="this.style.color= '#24292E'"
      onMouseOut="this.style.color='#33333D'">
      <i class="iconfont footer-social-item  icongithub-fill "></i>
    </a>
    
    
    
    
    
    <a href="mailto:youngyunzhao@163.com " target="_blank" onMouseOver="this.style.color='#FFBE5B'"
      onMouseOut="this.style.color='#33333D'">
      <i class="iconfont footer-social-item  iconmail"></i>
    </a>
    
  </div>
  <div class="footer-copyright"><p>Copyright© 2017 - 2020 ❤️ Flywith24</p></div>
</footer>
  
      <div class="fab fab-plus">
    <i class="iconfont iconplus"></i>
  </div>
  
  <div class="fab fab-daovoice">
    <i class="iconfont iconcomment"></i>
  </div>
  
  <div class="fab fab-up">
    <i class="iconfont iconcaret-up"></i>
  </div>
  
<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"debug":false,"model":{"jsonPath":"/live2dw/assets/shizuku.model.json"},"display":{"position":"left","width":150,"height":300},"mobile":{"show":"tfalse"},"log":false});</script></body>

<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>




<script src="https://cdn.bootcdn.net/ajax/libs/jquery.lazyload/1.9.1/jquery.lazyload.min.js"></script>




<script src="https://cdn.bootcss.com/fancybox/3.5.7/jquery.fancybox.min.js"></script>




<script src="/js/utils.js"></script>
<script src="/js/modules.js"></script>
<script src="/js/zui.js"></script>
<script src="/js/script.js"></script>




<script>
  (function (i, s, o, g, r, a, m) {
    i["DaoVoiceObject"] = r;
    i[r] = i[r] || function () {
      (i[r].q = i[r].q || []).push(arguments)
    }, i[r].l = 1 * new Date();
    a = s.createElement(o), m = s.getElementsByTagName(o)[0];
    a.async = 1;
    a.src = g;
    a.charset = "utf-8";
    m.parentNode.insertBefore(a, m)
  })(window, document, "script", ('https:' == document.location.protocol ? 'https:' : 'http:') +
    "//widget.daovoice.io/widget/0f81ff2f.js", "daovoice")
  daovoice('init', {
    app_id: "7785620b"
  }, {
    launcher: {
      disableLauncherIcon: true,
    },
  });
  daovoice('update');
</script>



<script>
  (function () {
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
      bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
    } else {
      bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
  })();
</script>


<script>
  var _hmt = _hmt || [];
  (function () {
    var hm = document.createElement("script");
    hm.src = "https://hm.baidu.com/hm.js?4c204d8bc027a0455b5fc642ac334ca8";
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(hm, s);
  })();
</script>










</html>